<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 积分商城模型
 * @author www.dingwei.cn
 */

class ConsumerMallModel extends MY_Model{
	
	public $tbMall = 'admin_integral_mall';
	public $tbLog = 'consumer_integral_log';//兑换记录
	
	public $tbConsumer = 'consumer';
	public $config = array(
	    'type'=>array('1' => '积分兑换','2' => '注册赠送','3' => '签到', '4' => '发布信息', '5' => '分享', '6' => '在线消费','7' => '积分调节','8' => '积分退回'),
        'status'=>array('1' => '处理中', '2' => '已完成', '3' => '退回积分'),
    );

	function __construct(){
		parent::__construct();
		
	}

    /**
     * 获取礼品信息
     * @param $id
     * @param int $status
     * @return array
     * @author zyl
     */
	public function getInfo($id, $status = 0){
		$this->db->where('id',$id);
		if ($status){
            $this->db->where('status',$status);
        }

		$tA = $this->getOne($this->tbMall);
		
		if ($tA){
			$tA['imgurl'] = getImage($tA['imgurl'],'xs');
		
			$imgs = json_decode($tA['showurl'],true);
			if ($imgs){
				$tA['showurl'] = array();
				foreach ($imgs as $ik => $iv){
					$tA['showurl'][] = getImage($iv,'og');
				}
			} 
			$tA['introduce'] = '<html><head><title></title></head><body style="width:94%;padding: 0 0.2rem;">'.$tA['introduce'].'</body>';
		}
		return $tA;
	}
	
	/**
	 * 新增|修改
	 * @param array $data 	数据
	 * @param number $id	id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function save($data , $id = 0){
		if ($id){
			$this->db->where('id',$id);
			$query = $this->update($this->tbMall, $data);
			return ($query === false ? false : true);
		}else {
			return $this->insert($this->tbMall, $data);
		}
	}
	
	/**
	 * 获取积分商城列表
	 * @param number $sort	排序方式
	 * @param number $page
	 * @return array|number|unknown
	 * @author zyl
	 */
	public function appGetList($sort = 0,$page = 1){
		
		$sortType = array(
				2 => 'integral asc', //积分 低->高
				3 => 'hot desc',    //热度 高->低
		);
		
		if ($sort == 1){
			//我可以兑换的商品
			$this->db->where('integral <=',get_instance()->userIntegral)->order_by('hot desc');
		}elseif (array_key_exists($sort, $sortType)){
			$this->db->order_by($sortType[$sort]);
		}
		
		$this->db->select('id,title,integral,hot,imgurl')
		->where('status',2);
		$tA = $this->appPage($this->tbMall, $page);
		
		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['imgurl'] = getImage($v['imgurl']);
		}
		return $tA['list'];
	}
	
	
	///////////////////////////////////////////////////////////
	//+----------------------------------------------------------
	//|	兑换记录  @author rable
	//+----------------------------------------------------------

	/**
	 * 获取订单记录
	 * @param unknown $consumerId
	 * @param number $type
	 * @param number $time
	 * @param number $page
	 * @param number $status
	 * @return array|number|unknown
	 * @author zyl
	 */
	public function appGetLogList($consumerId, $status = 0,$page = 1){
		
		if ($status){
			$this->db->where('status',$status);
		}
		
		$this->db
		->select('id,type,code,integral,product_param,address_param,status,addtime')
		->where('consumer_id',$consumerId)
		->where('type',1)
		->order_by('id desc');
		$tA = $this->appPage($this->tbLog, $page);
		
		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['type_desc'] = $this->_Type($v['type']);
			$tA['list'][$k]['type'] = $this->_Type($v['type'],true);
			$tA['list'][$k]['addtime'] = date('Y-m-d',$v['addtime']);
			
			$param = json_decode($v['product_param'],true);
			
			$tA['list'][$k]['title'] = isset($param['product_name'])?$param['product_name']:'';
			$tA['list'][$k]['one_integral'] = isset($param['integral'])?$param['integral']:'';
			$tA['list'][$k]['number'] = isset($param['number']) ?$param['number']:'';
			$tA['list'][$k]['icon'] = $param['icon'];
			$tA['list'][$k]['integral'] = abs($v['integral']);

			$tA['list'][$k]['address_param'] =  json_decode($v['address_param'],true);
			
			$tA['list'][$k]['status'] = $this->config['status'][$v['status']];
			
			unset($tA['list'][$k]['product_param']);
		}
		return $tA['list'];
	}
	
	/**
	 * 消费者获取积分记录
	 * @param unknown $consumerId
	 * @param number $type
	 * @param number $time
	 * @param number $page
	 * @param number $status
	 * @return array|number|unknown
	 * @author zyl
	 */
	public function appGetIntegralLogList($consumerId,  $type = 0, $time = 0, $page = 1){
	
		
		/**
		 * 时间筛选
		 */
		$starttime = '';
		$endtime = '';
		//类型存在
		if ( $type == 1 && ! $time){
			//默认今天
			$starttime = strtotime(date('Y-m-d 00:00:00'));
			$endtime = strtotime('+ 1 day',$starttime);
			
		}else if ($type == 1 && $time){
			//天
			if ( ! strtotime($time)){
				$this->appReturn(0,'时间格式错误');
			}
			$starttime = strtotime(date('Y-m-d 00:00:00',strtotime($time)));
			$endtime = strtotime('+ 1 day',$starttime);
			
		}else if ($type == 2 && $time){
			//月
			if ( ! strtotime($time)){
				$this->appReturn(0,'时间格式错误');
			}
			$starttime = strtotime(date('Y-m-01 00:00:00',strtotime($time)));
			$endtime = strtotime('+ 1 month',$starttime);
		}
//     	echo date('Y-m-d H:i:s',$starttime);
//     	echo date('Y-m-d H:i:s',$endtime);
		
		if ($starttime && $endtime){
			$this->db->where(array('addtime >='=>$starttime,'addtime <'=>$endtime));
		}
		
		$this->db
		->select('id,type,code,integral,product_param,address_param,status,addtime')
		->where('consumer_id',$consumerId)
		->order_by('id desc');
		$tA = $this->appPage($this->tbLog, $page);
		
		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['type_desc'] = $this->_Type($v['type']);
			$tA['list'][$k]['type'] = $this->_Type($v['type'],true);
			$tA['list'][$k]['addtime'] = date('Y-m-d',$v['addtime']);
			
			$param = json_decode($v['product_param'],true);
			
			$tA['list'][$k]['title'] = isset($param['product_name'])?$param['product_name']:$this->config['type'][$v['type']];;
			$tA['list'][$k]['one_integral'] = isset($param['integral'])?$param['integral']:'';
			$tA['list'][$k]['number'] = isset($param['number']) ?$param['number']:'';
			$tA['list'][$k]['icon'] = isset($param['icon']) ?getImage($param['icon'],'og'):getDefaultImg();
			
			$tA['list'][$k]['address_param'] =  json_decode($v['address_param'],true);
			
			$tA['list'][$k]['status'] = $this->config['status'][$v['status']];
			
			unset($tA['list'][$k]['product_param']);
		}
		return $tA['list'];
	}
	
	/**
	 * 购买记录类型
	 */
	private function _Type($key = NULL,$desc = FALSE){
		$type = array(
				1 => array('消费',''),
				2 => array('收入','+'),//注册赠送
				3 => array('收入','+'),//签到
				4 => array('收入','+'),//发布信息
				5 => array('收入','+'),//分享
				6 => array('消费',''),//在线消费
				7 => array('调整',''),//平台调整
                8 => array('收入',''),//积分退回
		);
		
		if ($key){
			
			if (isset($type[$key])){
				if ($desc){
					return $type[$key][1];
				}
				return $type[$key][0];
			}
			return '暂无类型';
		}
		
		return $type;
	}
	
	
	/**
	 * 新增|修改
	 * @param array $data 	数据
	 * @param number $id	id
	 * @return boolean|boolean|number
	 * @author zyl
	 */
	public function saveLog($data , $id = 0){
		if ($id){
			$this->db->where('id',$id);
			$query = $this->update($this->tbLog, $data);
			return ($query === false ? false : true);
		}else {
			return $this->insert($this->tbLog, $data);
		}
	}
	
	/**
	 * 获取礼品兑换记录信息
	 * @param integer $id id
     * @param bool    $isNumber      获取当天赠送积分的数量[heyu]
     * @return  array
	 * @author zyl
	 */
	public function getLogInfo($id, $isNumber = false){
	    if ($isNumber){
	        $time = strtotime(date('Y-m-d', time()));
            $this->db->select('count(id) as number, type')
                ->group_by('type')
                ->where('addtime > ',$time);
            $tA = $this->getAll($this->tbLog);

            $data = array();
            if (!empty($tA)) {
                foreach ($tA as $k => $v) {
                    $data[$v['type']] = $v['number'];
                }
            }
            unset($tA);
            return $data;
        }
		$this->db->select('a.code,a.id,a.consumer_id,a.type,a.integral,a.status,a.product_param,a.address_param,a.express_param,a.addtime,b.nickname')
		->join($this->tbConsumer.' b','a.consumer_id = b.id','left')
		->where(array('a.id'=>$id));
		
		$tA = $this->getOne($this->tbLog.' a');
		$tA['product_param'] = json_decode($tA['product_param'],true);
		$tA['address_param'] = json_decode($tA['address_param'],true);
		$tA['express_param'] = json_decode($tA['express_param'],true);
		$tA['status_name'] = $this->getStatus($tA['status'],true);
		return $tA;
	}
	
	///////////////////////////////////////////////////////////
	//+----------------------------------------------------------
	//|	后台方法  @author rable
	//+----------------------------------------------------------
	/**
	 * 后台获取列表
	 * @return array
	 */
	public function adminGetList(){
		$title = get('title');
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        if($sendDateFrom){
            $this->db->where('addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('addtime <= ', strtotime('+1day', $sendDateTo));
        }
		if ($title){
			$this->db->like('title',$title);
		}

		$iSortCol_0 = get('iSortCol_0');
		$sSortDir_0 = get('sSortDir_0');

		if ($iSortCol_0 == 2){
			$this->db->order_by('integral '.$sSortDir_0);
		}else if ($iSortCol_0 == 3){
			$this->db->order_by('hot '.$sSortDir_0);
		}else{
            $this->db->order_by('id desc ');
        }

		$status = get('status');
		if ($status){
			$this->db->where('status',$status);
		}
		return $this->pagination($this->tbMall);
	}

    /**
     * 后台获取列表
     * @return array
     */
    public function adminGetListById(){

        $consumerId = intval(get('consumer_id'));
        $type = intval(get('type'));
        $status = intval(get('status'));
        $code = trim(get('code'));
        $iSortCol_0 = get('iSortCol_0');
        $sSortDir_0 = get('sSortDir_0');

        if(!$consumerId)return array();

        if ($iSortCol_0 == 2){
            $this->db->order_by('integral '.$sSortDir_0);
        }

        if ($status){
            $this->db->where('status', $status);
        }

        if ($type){
            $this->db->where('type', $type);
        }

        if ($code){
            $this->db->where('code', $code);
        }

        $this->db->where('consumer_id', $consumerId);

        $this->db->select('code,type,status,integral')
                 ->order_by('addtime desc');

        return $this->pagination($this->tbLog);
    }

	/**
	 * 获取礼品订单信息
	 */
	public function adminGetLogList(){

		$title = trim(get('title'));
		$productName = trim(get('product_name'));
		$address = trim(get('address'));
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"
		$consumer_id= intval(get('consumer_id'));

		if ($title) {
            $this->db->like('c.title', $title);
        }
        if ($productName) {
            $this->db->like('a.product_param', $productName);
        }
        if ($address) {
            $this->db->like('a.address_param', $address);
        }

		$code = get('code');
		if ($code){
			$this->db->like('a.code',$code);

		}
		
		$nickname = get('nickname');
		if ($nickname){
			$this->db->like('b.nickname',$nickname);
		}
		
		$status = get('status');
		if ($status){
			$this->db->where('a.status',$status);
		}

		if($consumer_id){
            $this->db->where('a.consumer_id',$consumer_id);
        }
        if($sendDateFrom){
            $this->db->where('a.addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('a.addtime <= ', strtotime('+1day', $sendDateTo));
        }
        if ($iSortCol_0 == 4){
            $this->db->order_by('a.integral', $sSortDir_0);
        }else if ($iSortCol_0 == 7){
            $this->db->order_by('a.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('a.id desc');
        }

		$this->db->select('a.id,a.code,a.type,a.integral,a.status,a.product_param,a.address_param,a.express_param,a.addtime,b.nickname')
				 ->join($this->tbConsumer.' b','a.consumer_id = b.id','left')
				 ->where(array('a.type'=>1));
		 $tA = $this->pagination($this->tbLog.' a');
		 return $tA;
		 
	}

    /**
     * 删除积分礼品
     * @param $id
     * @return bool
     * @author heyu
     */
	public function deleteMall($id){
        if (!$id){
            return false;
        }
        $this->db->where(array('id' => $id));
        return $this->delete($this->tbMall);
    }

    /**
     * 获取状态显示样式
     * @param null $status
     * @param bool $show
     * @return mixed|string
     */
    public function getStatus($status = null, $show = false){

        $config = $this->config['status'];
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }else if($status == 3){
            return '<span class="label label-warning">'.$config[$status].'</span>';
        }

        return'';
    }

    /**
     * 赠送积分
     * @param $type int 1：消费  2：注册赠送 3签到 4发布信息 5分享 6在线消费 7平台调整
     * @param $userId 消费者id
     * @param $userIntegral 消费者当前账号积分
     * 3 签到赠送积分数量(每日限一次)
     * 4 发布信息赠送积分数量(每日首次)
     * 5 分享赠送数量( 每日限5次)
     * @author heyu
     */
    public function _addIntegral($type, $consumerId, $userIntegral){
        if(!$type || !$consumerId)return array('status' => 0, 'message' => '积分奖励失败');
        // 签到赠送积分数量(每日限一次)
        get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');

        if ($type == 3){
            $name = 'sign_integral_number';
        }else if($type == 4){
            $name = 'publish_integral_number';
        }else if($type == 5){
            $name = 'share_integral_number';
        }else{
            return;
        }
        // 查看当日是否已赠送积分
        $logInfo = $this->getLogInfo(0, true);
        if (!empty($logInfo)){
            $count = isset($logInfo[$type]) ? $logInfo[$type] : 0;
            if ($type == 5) {
                if ($count >= 5) {
                    return;
                }
            }else if ($count){
                return;
            }
        }
        $number = $this->mSetting->get($name); // 发布信息赠送数量
        if ($number > 0) {
            $integral = $this->mUser->save(array('integral' =>$userIntegral+$number), $consumerId);
            if (!$integral) {
                return array('status' => 0, 'message' => '新增积分失败');
            }
            // 添加积分记录
            $integralLogData = array(
                'consumer_id' => $consumerId,
                'type' => $type,
                'integral' => $number,
                'status' => 2,
                'addtime' => time(),
            );
            $integralLog = $this->saveLog($integralLogData);
            if (!$integralLog) {
                return array('status' => 0, 'message' => '添加积分记录失败');
            }
        }

        return array('status' => 1, 'message' => '积分奖励成功');
    }
}
